import {validateMobile} from "../../utils/validate";
import {showToastError, showToastSuccess} from "../../utils/tool";
import {simpleGet, simplePost} from "../../utils/request";

const smsBtnText = '发送验证码'
const smsTime = 180

Component({
    options:{
        styleIsolation: 'apply-shared'
    },
    properties: {
        mobile:{type:String, value:''},
        type:{type:String, value:''},
    },
    data: {
        sms:{
            code:'',
            btnText: smsBtnText,
            loading: false,
        }
    },
    methods: {
        inputChange(e){
            this.triggerEvent('codeChange', {
                code:e.detail.value
            })
        },
        sendSms(){
            let curSmsTime = smsTime
            const {mobile, sms, type} = this.data
            if (!mobile || !validateMobile(mobile)){
                showToastError("手机号格式错误")
                return
            }
            this.setData({
                [`sms.loading`]: true,
            })


            simplePost('/public/sendVerifySms', {
                mobile: mobile,
                type:type,
            }).then(res => {
                showToastSuccess("验证码已发送")
                this.setData({
                    [`sms.btnText`]:`倒计时（${curSmsTime}）`
                })

                let sVal = setInterval(() => {
                    curSmsTime--
                    this.setData({
                        [`sms.btnText`]:`倒计时（${curSmsTime}）`
                    })
                    if (curSmsTime == 0){
                        clearInterval(sVal)
                        this.setData({
                            [`sms.btnText`]: smsBtnText,
                            [`sms.loading`]: false,
                        })
                    }
                },1000)
            }).catch(err =>{
                this.setData({
                    [`sms.loading`]:false
                })
            })
        }
    }
});
